package com.party.mobile.biz.distributor;

import com.google.common.base.Function;
import com.google.common.collect.Sets;
import com.party.common.paging.Page;
import com.party.common.utils.*;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.article.Article;
import com.party.core.model.crowdfund.ProjectWithAuthor;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.crowdfund.SupportWithMember;
import com.party.core.model.distributor.*;
import com.party.core.model.goods.Goods;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.system.MemberSysRole;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysRole;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.count.IDataCountService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.distributor.IDistributorTargetAttacheService;
import com.party.core.service.goods.IGoodsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysRoleService;
import com.party.mobile.biz.analyze.MemberCopartnerDetailBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.web.dto.crowdfund.input.StatisticsInput;
import com.party.mobile.web.dto.distributor.input.ApplyDistributorInput;
import com.party.mobile.web.dto.distributor.input.DistributorInput;
import com.party.mobile.web.dto.distributor.input.DistributorListInput;
import com.party.mobile.web.dto.distributor.input.GetDistributorInput;
import com.party.mobile.web.dto.distributor.output.DistributorFillOutput;
import com.party.mobile.web.dto.distributor.output.DistributorListOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Nullable;
import java.util.Date;
import java.util.List;

/**
 * 分销业务接口
 * Created by wei.li
 *
 * @date 2017/3/1 0001
 * @time 17:26
 */

@Service
public class DistributorBizService {

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private IDistributorCountService distributorCountService;

    @Autowired
    private IDistributorDetailService distributorDetailService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IDistributorTargetAttacheService distributorTargetAttacheService;

    @Autowired
    private IDataCountService dataCountService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IMemberSysRoleService memberSysRoleService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private FileBizService fileBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 分销
     * @param input 输入视图
     * @param currentUser 当前用户
     * @return 分销者编号
     */
    @Transactional
    public void distributor(GetDistributorInput input, CurrentUser currentUser, DistributorFunction distributorFunction){

        DistributorRelation distributorRelation
                = distributorRelationService.get(input.getType(), input.getTargetId(), currentUser.getId());
        if (distributorRelation != null){
            throw new BusinessException(PartyCode.DISTRIBUTOR_EXSIT, "已经分销");
        }

        distributorRelation = GetDistributorInput.transform(input);
        if (DistributorRelationType.ACTIVITY.getCode().equals(input.getType())
                || DistributorRelationType.CROWDFUND_REPRESENT.getCode().equals(input.getType())
                || DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(input.getType())
                || DistributorRelationType.COURSE_DISTRIBUTION.getCode().equals(input.getType())) {
            //生成分销
            Activity activity = activityService.get(input.getTargetId());
            distributorRelation.setTitle(activity.getTitle());
            distributorRelation.setPic(activity.getPic());
            if (null != activity.getPrice()) {
                distributorRelation.setPrice(activity.getPrice());
            }
            distributorRelation.setTargetEndDate(activity.getEndTime());
        } else if (DistributorRelationType.BZ_GOODS.getCode().equals(input.getType()) || DistributorRelationType.DZ_GOODS.getCode().equals(input.getType())) {
            Goods goods = goodsService.get(input.getTargetId());
            distributorRelation.setTitle(goods.getTitle());
            distributorRelation.setPic(goods.getPicsURL());
            distributorRelation.setPrice(goods.getPrice());
            distributorRelation.setTargetEndDate(goods.getEndTime());
        } else if (DistributorRelationType.ARTICLE.getCode().equals(input.getType())) {
            Article article = articleService.get(input.getTargetId());
            distributorRelation.setTitle(article.getTitle());
            distributorRelation.setPic(article.getPic());
            distributorRelation.setPrice(0f);
            distributorRelation.setTargetEndDate(DateUtils.addYear(DateUtils.getTodayDate(), 1));
        }
        distributorRelation.setDistributorId(currentUser.getId());
        distributorRelationService.insert(distributorRelation);
        this.distributorCount(distributorRelation);
        this.targetCount(input.getTargetId());

        try {
            Activity activity = activityService.get(input.getTargetId());
            String filePath = fileBizService.getUploadCIPath("represent", currentUser.getId());
            String content = "project/represent_target.html?id=" + activity.getId()+"&parentId="+activity.getMember()+"&distributorId="+distributorRelation.getDistributorId();
            String previewPicUrl = fileBizService.uploadCloudOut(distributorRelation.getId(), filePath, content, activity.getMember());
            if (previewPicUrl == null) {
                logger.error("生成联合发起人二维码异常——众筹项目id= " + activity.getId() + "——代言id=" + distributorRelation.getId());
            }
        } catch (Exception e) {
            logger.error("生成联合发起人二维码异常", e);
        }


        if (StringUtils.isNotEmpty(input.getParentId())) {
            if (DistributorRelationType.ACTIVITY.getCode().equals(input.getType())
                    || DistributorRelationType.CROWDFUND_REPRESENT.getCode().equals(input.getType())
                    || DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(input.getType())) {
                try {
                    // 机构关系用户
                    PartnerMember partnerMember = new PartnerMember();
                    partnerMember.setPartnerId(input.getParentId());
                    partnerMember.setMemberId(currentUser.getId());
                    partnerMemberService.getSet(partnerMember);
                    // 个人统计表添加数据
//                memberPersonalCountBizService.getSet(partnerMember.getPartnerId(), partnerMember.getMemberId());
                } catch (Exception e) {
                    logger.error("分销添加机构关系用户异常", e);
                }
            }
        }

        if (null != distributorFunction){
            distributorFunction.success(distributorRelation.getId());
        }
    }

    /**
     * 分销
     * @param input 输入视图
     * @param currentUser 当前用户
     */
    public void distributor(DistributorInput input, CurrentUser currentUser){
        this.distributor(DistributorInput.transform(input), currentUser, new DistributorFunction() {
            @Nullable
            @Override
            public void success(@Nullable String distributorId) {
                //新增附属信息
                DistributorTargetAttache distributorTargetAttache = new DistributorTargetAttache();
                distributorTargetAttache.setStyle(input.getStyle());
                distributorTargetAttache.setContent(input.getDeclaration());
                distributorTargetAttache.setDistributorRelationId(distributorId);
                distributorTargetAttacheService.insert(distributorTargetAttache);
            }
        });
    }

    /**
     * 分销统计
     * @param distributorRelation 分销关系
     */
    public void distributorCount(DistributorRelation distributorRelation){

        //分销统计
        DistributorCount distributorCount = new DistributorCount(distributorRelation.getId());
        distributorCountService.insert(distributorCount);

        //父分销关系
        DistributorRelation parent
                = distributorRelationService.get(distributorRelation.getType(), distributorRelation.getTargetId(), distributorRelation.getParentId());
        //是不是存在
        if (null != parent){
            DistributorCount parentCount = distributorCountService.findByRelationId(parent.getId());
            parentCount.setShareNum(parentCount.getShareNum() + 1);
            distributorCountService.update(parentCount);
        }

    }

    /**
     * 统计目标的分销量
     * @param targetId 目标编号
     */
    public void targetCount(String targetId){
       Activity activity = activityService.get(targetId);
        if (null != activity){
            activity.setShareNum(activity.getShareNum() + 1);
            activityService.update(activity);
            return;
        }
        Goods goods = goodsService.get(targetId);
        if (null != goods){
            goods.setShareNum(goods.getShareNum() + 1);
            goodsService.update(goods);
            return;
        }
        Article article = articleService.get(targetId);
        if (null != article){
            article.setShareNum(article.getShareNum() + 1);
            articleService.update(article);
            return;
        }
    }

    /**
     * 分销报名统计
     *
     * @param input 输入视图
     */
    public boolean setDistributorData(ApplyDistributorInput input, DistributorRelation distributorRelation) {
        //保存分销详情
        DistributorDetail distributorDetail = distributorDetailService.get(input.getTargetId(), input.getType(), distributorRelation.getId());
        if (null == distributorDetail) {
            distributorDetail = ApplyDistributorInput.transform(input);
            distributorDetail.setDistributorRelationId(distributorRelation.getId());
            distributorDetailService.insert(distributorDetail);
            return true;
        }
        return false;
    }

    /**
     * 分销报名统计
     * @param input 输入视图
     */
    public boolean setDistributorData(ApplyDistributorInput input){
        DistributorRelation distributorRelation
                = distributorRelationService.get(input.getDistributorType(),
                input.getDistributorTargetId(),input.getDistributorId());

        if (null == distributorRelation){
            throw new BusinessException("分销关系不存在");
        }

        //保存分销详情
        DistributorDetail distributorDetail = distributorDetailService.get(input.getTargetId(), input.getType(), distributorRelation.getId());
        if (null == distributorDetail) {
            distributorDetail = ApplyDistributorInput.transform(input);
            distributorDetail.setDistributorRelationId(distributorRelation.getId());
            distributorDetailService.insert(distributorDetail);

            this.distributorCount(distributorRelation.getId(), input.getType());
            return true;
        }
        return false;
    }

    /**
     * 分销统计报名
     * @param distributorRelationId 分销关系编号
     * @param targetId 统计目标编号
     * @param type 类型
     */
    @Transactional
    public void setDistributorData(String distributorRelationId, String targetId, Integer type){
        DistributorRelation distributorRelation = distributorRelationService.get(distributorRelationId);
        if (null == distributorRelation){
            throw new BusinessException("分销关系不存在");
        }

        DistributorDetail distributorDetail = new DistributorDetail();
        distributorDetail.setType(type);
        distributorDetail.setTargetId(targetId);
        distributorDetail.setDistributorRelationId(distributorRelationId);
        distributorDetailService.insert(distributorDetail);
        this.distributorCount(distributorRelation.getId(), type);
    }

    /**
     * 统计数据
     *
     * @param disRelationId 分销关系编号
     * @param type          类型
     * @param payment       金额
     * @param isSuccess     成功状态
     */
    @Transactional
    public void distributorCount(String disRelationId, Integer type, Float payment, boolean isSuccess) {
        DistributorCount distributorCount = distributorCountService.findByRelationIdLock(disRelationId);
        if (null == distributorCount) {
            logger.error("分销统计不存在");
            return;
        }

        List<DistributorDetail> distributorDetails = distributorDetailService
                .findByRelationId(disRelationId, type);
        if (DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode().equals(type)) {
            distributorCount.setApplyNum(distributorDetails.size());
        } else if (DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode().equals(type)) {
            distributorCount.setSalesNum(distributorDetails.size());
        } else if (DistributorDetailType.DISTRIBUTOR_TYPE_CROWDFUN.getCode().equals(type)) {
            distributorCount.setCrowdfundNum(distributorDetails.size());
        } else if (DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode().equals(type)) {
            distributorCount.setFavorerNum(distributorDetails.size());
        } else {
            throw new BusinessException("分销详情类型错误");
        }

        Float amount = BigDecimalUtils.add(distributorCount.getFavorerAmount(), payment);
        amount = BigDecimalUtils.round(amount, 2);
        distributorCount.setFavorerAmount(amount);

        if (isSuccess) {
            distributorCount.setSuccessNum(distributorCount.getSuccessNum() + 1);
        }

        distributorCountService.update(distributorCount);
    }

    /**
     * 统计数据
     * @param distributorRelationId 分销关系编号
     * @param type 类型
     */

    @Transactional
    public  void distributorCount(String distributorRelationId, Integer type){
        DistributorCount distributorCount = distributorCountService.findByRelationIdLock(distributorRelationId);
        if (null == distributorCount){
            throw new BusinessException("分销统计不存在");
        }

        List<DistributorDetail> distributorDetails = distributorDetailService
                .findByRelationId(distributorRelationId, type);
        if (DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode().equals(type)) {
            distributorCount.setApplyNum(distributorDetails.size());
        }
        else if (DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode().equals(type)){
            distributorCount.setSalesNum(distributorDetails.size());
        }
        else if (DistributorDetailType.DISTRIBUTOR_TYPE_CROWDFUN.getCode().equals(type)){

            distributorCount.setCrowdfundNum(distributorDetails.size());
        }
        else if (DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode().equals(type)){
            distributorCount.setFavorerNum(distributorDetails.size());
        }
        else {
            throw new BusinessException("分销详情类型错误");
        }
        distributorCountService.update(distributorCount);
    }


    /**
     * 是否是自己的分销
     * @param currentUser 请求参数
     * @param targetId 活动编号
     * @param distributorId 分销编号
     * @param parentId 父分销编号
     * @return
     */
    public boolean isMyDistribution(CurrentUser currentUser,Integer targetType, String targetId, String distributorId, String parentId){
        DistributorRelation distributorRelation
                = distributorRelationService.get(targetType, targetId, distributorId);
        if (null == distributorRelation){
            throw new BusinessException("分销关系不存在");
        }

        boolean isMyDistribution = false;
        if (null != currentUser){
            //是否是我的分销
            if (currentUser.getId().equals(distributorRelation.getDistributorId())){
                isMyDistribution = true;
            }
        }
        return isMyDistribution;
    }


    /**
     * 查询分销统计列表
     * @param distributorListInput 输入视图
     * @param page 分页
     * @return 统计列表
     */
    public List<DistributorListOutput> list(DistributorListInput distributorListInput, CurrentUser currentUser, Page page){
        List<WithCount> withCountList
                = distributorRelationService.listWithCount(distributorListInput.getStatus(),
                distributorListInput.getType(), distributorListInput.getSort(), currentUser.getId(), page);

        List<DistributorListOutput> outputList = LangUtils.transform(withCountList, new Function<WithCount, DistributorListOutput>() {
            @Nullable
            @Override
            public DistributorListOutput apply(@Nullable WithCount withCount) {
                DistributorListOutput distributorListOutput = DistributorListOutput.transform(withCount);
                Member member = memberService.get(withCount.getDistributorId());
                distributorListOutput.setDistributorLogo(member.getLogo());
                distributorListOutput.setDistributorName(member.getRealname());
                return distributorListOutput;
            }
        });
        return outputList;
    }


    /**
     * 刷新当前统计
     * @param distributorCount 分销统计
     * @param distributionType 分销类型
     */
    @Transactional
    public void refreshCount(DistributorCount distributorCount, Integer distributionType){

        //下级分销量
        DistributorRelation distributorRelation = distributorRelationService.get(distributorCount.getDistributorRalationId());
        if (null != distributorRelation){
            List<WithCount> withCountList = distributorRelationService.findByParentId(distributorRelation.getDistributorId(), distributorRelation.getTargetId());
            distributorCount.setShareNum(withCountList.size());
        }

        //报名量
        List<DistributorDetail> applyList = distributorDetailService.applyList(distributorCount.getDistributorRalationId());
        distributorCount.setApplyNum(applyList.size());

        //下单量
        List<DistributorDetail> buyList = distributorDetailService.buyList(distributorCount.getDistributorRalationId());
        distributorCount.setSalesNum(buyList.size());

        if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(distributionType)
                || DistributorRelationType.CROWDFUND_REPRESENT.getCode().equals(distributionType)) {
            this.reviseCrowdfund(distributorCount, distributionType);
        }

        distributorCount.setUpdateDate(new Date());
        distributorCountService.update(distributorCount);
    }


    /**
     * 校正众筹数据
     * @param distributorCount 分销统计
     * @param distributionType 分销类型
     */
    @Transactional
    public void reviseCrowdfund(DistributorCount distributorCount, Integer distributionType){

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        projectWithAuthor.setRelationId(distributorCount.getDistributorRalationId());
        List<ProjectWithAuthor> projectWithAuthorList = projectService.listPage(projectWithAuthor, null);



        List<String> projectIds = LangUtils.transform(projectWithAuthorList, new Function<ProjectWithAuthor, String>() {
            @Nullable
            @Override
            public String apply(@Nullable ProjectWithAuthor projectWithAuthor) {
                if (null == projectWithAuthor){
                    return null;
                }
                return projectWithAuthor.getId();
            }
        });


        distributorCount.setCrowdfundNum(projectIds.size());

        if (projectIds != null && projectIds.size() > 0){
            List<SupportWithMember> crowdSupportList = supportService.findByProjectIds(Sets.newHashSet(projectIds));
            List<String> crowdSuppIds = LangUtils.transform(crowdSupportList, new Function<Support, String>() {
                @Nullable
                @Override
                public String apply(@Nullable Support input) {
                    return input.getId();
                }
            });
            List<SupportWithMember> distribSupportList = supportService.findByRelationId(distributorCount.getDistributorRalationId());
            List<String> distSuppIds = LangUtils.transform(distribSupportList, new Function<Support, String>() {
                @Nullable
                @Override
                public String apply(@Nullable Support input) {
                    return input.getId();
                }
            });
            crowdSuppIds.removeAll(distSuppIds);

            for (String supportId : crowdSuppIds) {
                Support support = supportService.get(supportId);
                DistributorDetail distributorDetail = distributorDetailService.get(support.getOrderId(),
                        DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode(),
                        distributorCount.getDistributorRalationId());
                if (null != distributorDetail) {
                    continue;
                }
                distributorDetail = new DistributorDetail();
                distributorDetail.setTargetId(support.getOrderId());
                distributorDetail.setDistributorRelationId(distributorCount.getDistributorRalationId());
                distributorDetail.setCreateDate(support.getCreateDate());
                distributorDetail.setUpdateDate(support.getUpdateDate());
                distributorDetail.setType(DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode());
                distributorDetailService.insert(distributorDetail);
            }

            if (DistributorRelationType.CROWDFUND_REPRESENT.getCode().equals(distributionType)) {
                Integer favorerNum = 0;
                Float favorerAmount = 0f;
                //矫正统计数据
                for (ProjectWithAuthor projectWithAuthor1 : projectWithAuthorList) {
                    favorerNum = favorerNum + projectWithAuthor1.getFavorerNum();
                    favorerAmount = BigDecimalUtils.add(favorerAmount, projectWithAuthor1.getActualAmount());
                    favorerAmount = BigDecimalUtils.round(favorerAmount, 2);
                }
                distributorCount.setFavorerNum(favorerNum);
                distributorCount.setFavorerAmount(favorerAmount);
            }

            if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(distributionType)) {
                Float favorerAmount = 0f;
                //矫正统计数据
                for (SupportWithMember support : crowdSupportList) {
                    favorerAmount = BigDecimalUtils.add(favorerAmount, support.getPayment());
                    favorerAmount = BigDecimalUtils.round(favorerAmount, 2);
                }
                distributorCount.setFavorerNum(crowdSupportList.size());
                distributorCount.setFavorerAmount(favorerAmount);
            }

            ProjectWithAuthor projectWithAuthor1 = new ProjectWithAuthor();
            projectWithAuthor1.setRelationId(distributorCount.getDistributorRalationId());
            projectWithAuthor1.setIsSuccess(1);
            List<ProjectWithAuthor> projectWithAuthorList2 = projectService.listPage(projectWithAuthor1, null);
            distributorCount.setSuccessNum(projectWithAuthorList2.size());
        } else {
            distributorCount.setFavorerNum(0);
            distributorCount.setFavorerAmount(0f);
        }
    }


    /**
     * 获取填写详情
     * @param id 编号
     * @param type 类型
     * @return 输出视图
     */
    public DistributorFillOutput getFill(String id , Integer type){
        DistributorFillOutput distributorFillOutput = new DistributorFillOutput();
        if (type.equals(DistributorRelationType.ACTIVITY.getCode())){
            Activity activity = activityService.get(id);
            distributorFillOutput = DistributorFillOutput.transform(activity);
            distributorFillOutput.setType(type);
        }
        else if (type.equals(DistributorRelationType.DZ_GOODS.getCode()) || type.equals(DistributorRelationType.BZ_GOODS.getCode())){
            Goods goods = goodsService.get(id);
            distributorFillOutput = DistributorFillOutput.transform(goods);
            distributorFillOutput.setPic(goods.getPicsURL());
            distributorFillOutput.setType(type);
        }
        else if (type.equals(DistributorRelationType.ARTICLE.getCode())){
            Article article = articleService.get(id);
            distributorFillOutput = DistributorFillOutput.transform(article);
            distributorFillOutput.setType(type);
        }
        return distributorFillOutput;
    }

    public void addCopartner(String distributorId) {
        Member member = memberService.get(distributorId);
        member.setIsCopartner(YesNoStatus.YES.getCode());
        member.setType(Member.MEMBER_PERSONAL);
        member.setUpdateDate(null);
        memberService.update(member);

        boolean copartnerFlag = sysRoleService.hasRole(member.getId(), RoleEnum.COPARTNER_ROLE.getCode());
        if (!copartnerFlag) {
            SysRole t = new SysRole();
            t.setCode(RoleEnum.COPARTNER_ROLE.getCode());
            t.setType(RoleType.SYSTEM_ROLE.getCode());
            SysRole copartner = sysRoleService.uniqueProperty(t);
            MemberSysRole memberSysRole = new MemberSysRole(member.getId(), copartner.getId());
            memberSysRoleService.insert(memberSysRole);
        }
    }

    /**
     * 根据目标编号找分销者编号
     *
     * @param targetId 目标编号
     * @return 分销者编号
     */
    public String getDistributorId(String targetId) {
        DistributorDetail distributorDetail = distributorDetailService.findByTargetId(targetId);
        if (distributorDetail != null) {
            DistributorRelation distributorRelation = distributorRelationService.get(distributorDetail.getDistributorRelationId());
            if (distributorRelation != null) {
                return distributorRelation.getDistributorId();
            }
        }
        return null;
    }

    /**
     * 根据目标编号找分销者编号
     *
     * @param targetId 目标编号
     * @return 分销者编号
     */
    public DistributorRelation getDistributorRelation(String targetId) {
        DistributorDetail distributorDetail = distributorDetailService.findByTargetId(targetId);
        if (distributorDetail != null) {
            DistributorRelation distributorRelation = distributorRelationService.get(distributorDetail.getDistributorRelationId());
            return distributorRelation;
        }
        return null;
    }

    /**
     * 根据目标编号找分销关系类型
     *
     * @param targetId 目标编号
     * @return 分销关系类型
     */
    public Integer getDistributorType(String targetId) {
        DistributorDetail distributorDetail = distributorDetailService.findByTargetId(targetId);
        if (distributorDetail != null) {
            DistributorRelation distributorRelation = distributorRelationService.get(distributorDetail.getDistributorRelationId());
            if (distributorRelation != null) {
                return distributorRelation.getType();
            }
        }
        return null;
    }

    /**
     * 统计报名成功订单
     *
     * @param input 输入视图
     */
    public void statisticsOrder(StatisticsInput input) {
        DistributorRelation distributorRelation = getDistributorRelation(input.getApplyId());

        if (null != distributorRelation) {
            ApplyDistributorInput applyDistributorInput = new ApplyDistributorInput();
            applyDistributorInput.setDistributorId(distributorRelation.getDistributorId());
            applyDistributorInput.setDistributorParentId(distributorRelation.getParentId());
            applyDistributorInput.setDistributorType(distributorRelation.getType());
            applyDistributorInput.setDistributorTargetId(distributorRelation.getTargetId());
            applyDistributorInput.setTargetId(input.getOrderId());
            applyDistributorInput.setType(DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode());
            boolean result = setDistributorData(applyDistributorInput);
            if (result) {

                DistributorCount distributorCount = distributorCountService.findByRelationId(distributorRelation.getId());
                if (null == distributorCount) {
                    throw new BusinessException("分销统计不存在");
                }

                Float amount = BigDecimalUtils.add(distributorCount.getFavorerAmount(), input.getPayment());
                amount = BigDecimalUtils.round(amount, 2);
                distributorCount.setFavorerAmount(amount);

                distributorCountService.update(distributorCount);

                try {
                    memberCopartnerDetailBizService.updateOrderAnalyze(input.getOrderId(), input.getPayment());
                } catch (Exception e) {
                    logger.error("实时更新合伙人订单统计数异常", e);
                }
            }
        }
    }

    @Transactional
    public String activityCancelApply(String targetId) {
        DistributorDetail applyDetail = distributorDetailService.findByTargetId(targetId);
        if (null != applyDetail) {
            try {
                DistributorCount distributorCount = distributorCountService.findByRelationId(applyDetail.getDistributorRelationId());
                if (null != distributorCount) {
                    distributorCount.setApplyNum(distributorCount.getApplyNum() - 1);
                    if (distributorCount.getApplyNum() < 0) {
                        distributorCount.setApplyNum(0);
                    }
                    distributorCountService.update(distributorCount);
                }
                distributorDetailService.delete(applyDetail.getId());
            } catch (Exception e) {
                logger.error("活动/课程退款后，分销数据处理异常", e);
            }
            return applyDetail.getDistributorRelationId();
        }
        return null;
    }

    /**
     * 处理分销
     *
     * @param input    输入参数
     * @param memberId 用户id
     */
    public void dealActivityDistribution(StatisticsInput input, String memberId, Function fn) {
        try {
            //分销统计
            DistributorRelation distributorRelation = getDistributorRelation(input.getApplyId());
            if (null != distributorRelation) {
                Integer findCount = 0;

                MemberAct query = new MemberAct();
                query.setMemberId(memberId);
                query.setActId(input.getDistributorTargetId());
                List<MemberAct> memberActs = memberActService.list(query);
                for (MemberAct item : memberActs) {
                    DistributorDetail applyDetail = distributorDetailService.get(item.getOrderId()
                            , DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode(), distributorRelation.getId());
                    if (null != applyDetail) {
                        findCount++;
                        distributorDetailService.delete(applyDetail.getId());
                    }
                }

                DistributorDetail distributorDetail = new DistributorDetail();
                distributorDetail.setTargetId(input.getOrderId());
                distributorDetail.setDistributorRelationId(distributorRelation.getId());
                distributorDetail.setType(DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode());
                distributorDetailService.insert(distributorDetail);

                // 如果已经保存分销详情，就不用再保存
                if (findCount == 0) {
                    distributorCount(distributorRelation.getId(), DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode());

                    DistributorCount distributorCount = distributorCountService.findByRelationId(distributorRelation.getId());
                    if (null == distributorCount) {
                        throw new BusinessException("分销统计不存在");
                    }

                    Float amount = BigDecimalUtils.add(distributorCount.getFavorerAmount(), input.getPayment());
                    amount = BigDecimalUtils.round(amount, 2);
                    distributorCount.setFavorerAmount(amount);

                    distributorCountService.update(distributorCount);

                    try {
                        memberCopartnerDetailBizService.updateOrderAnalyze(input.getOrderId(), input.getPayment());
                    } catch (Exception e) {
                        logger.error("实时更新合伙人订单统计数异常", e);
                    }

                    fn.apply(null);
                }
            }
        } catch (Exception e) {
            logger.error("报名的分销统计异常", e);
        }
    }

    /**
     * @param disRelationType 分销关系类型
     * @return
     * @Author yifeng
     * @Description 判断分销关系类型是否为众筹或者课程
     * @Date 16:42 2019/4/18
     **/
    public boolean isCrowOrCourse(Integer disRelationType) {
        if (null == disRelationType) {
            return false;
        }
        if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(disRelationType)
                || DistributorRelationType.COURSE_DISTRIBUTION.getCode().equals(disRelationType)) {
            return true;
        }
        return false;
    }
}
